package me.ezitku.base.extensions.BroadCastReceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.fragment.app.Fragment
import me.ezitku.base.extensions.tryCatch

/**
 * BroadCastReceiver
 */

private val String.getFilter: IntentFilter
    get() = IntentFilter().apply { addAction(this@getFilter) }

private val Array<String>.getFilter: IntentFilter
    get() = IntentFilter().apply { this@getFilter.forEach { addAction(it) } }


private fun getBroadcast(onReceive: (intent: Intent) -> Unit): BroadcastReceiver {
    return object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            onReceive.invoke(intent)
        }
    }
}

fun Context.createBreceiver(filterActions: Array<String>, onReceive: (intent: Intent) -> Unit) {
    tryCatch { registerReceiver(getBroadcast { onReceive(it) }, filterActions.getFilter) }
}

fun Context.createBreceiver(filterAction: String, onReceive: (intent: Intent) -> Unit): BroadcastReceiver {
    var broadcast = getBroadcast { onReceive(it) }
    tryCatch {
        var broadcast = getBroadcast { onReceive(it) }
        registerReceiver(broadcast, filterAction.getFilter)
//        registerReceiver(getBroadcast { onReceive(it) }, filterAction.getFilter)
    }
    return broadcast

}


fun Fragment.createBreceiver(filterAction: String, onReceive: (intent: Intent) -> Unit) {
    activity!!.createBreceiver(filterAction, onReceive)
}


fun Fragment.createBreceiver(filterActions: Array<String>, onReceive: (intent: Intent) -> Unit) {
    activity!!.createBreceiver(filterActions, onReceive)
}


fun Context.sendBReceiver(action: String) {
    sendBroadcast(Intent(action))
}

fun Fragment.sendBReceiver(action: String) {
    activity!!.sendBroadcast(Intent(action))
}